
const EXPLODE_SPRITESHEET_URL = '/images/plane/explode.json';

define([
  'require', 'pool'
], function (require, pool) {
  'use strict';

  var _this = {};

  function init (app, container) {
    var self = _this;
    self.loading = true;
    self.container = container;
    self.explosionPoolName = 'EXPLOSION_POOL';
    self.explosionTexs = [];
    self.explosingArr = [];

    new PIXI.loaders.Loader()
      .add('explosionImg', EXPLODE_SPRITESHEET_URL)
      .load(function (loader, res) {
        for (let frameId in res.explosionImg.data.frames) {
          self.explosionTexs.push(PIXI.Texture.fromFrame(frameId));
        }

        for (let i = 0; i < 5; i++) {
          var explosion = newExplosion();
          container.addChild(explosion);
          self.explosingArr.push(explosion);
          pool.put(self.explosionPoolName, explosion);
        }
        self.loading = false;
      });
  }

  function explode (pos) {
    var explosion = pool.get(_this.explosionPoolName);
    if (explosion == null) {
      explosion = newExplosion();
      _this.container.addChild(explosion);
      _this.explosingArr.push(explosion);
    }

    explosion.visible = true;
    explosion.position.x = pos.x;
    explosion.position.y = pos.y;
    explosion.gotoAndPlay(0);
  }

  function newExplosion () {
    var explosion = new PIXI.extras.AnimatedSprite(_this.explosionTexs); 
    explosion.visible = false;
    explosion.anchor.set(0.5);
    explosion.scale.set(2);
    explosion.loop = false;
    explosion.onComplete = onComplete;
    explosion.animationSpeed = 0.5;
    return explosion;
  }

  function onComplete () {
    this.visible = false;
    pool.put(_this.explosionPoolName, this);
  }

  return {
    init: init,
    explode: explode
  }

});
